package com.hanhai.zrb.backend.web.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.propertyeditors.CustomCollectionEditor;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.hanhai.zrb.api.biz.service.CityInfoService;
import com.hanhai.zrb.api.biz.service.IndustryService;
import com.hanhai.zrb.api.biz.service.MessageQueryService;
import com.hanhai.zrb.api.biz.service.SysDictionaryService;
import com.hanhai.zrb.api.biz.service.UserBlacklistService;
import com.hanhai.zrb.api.biz.service.UserDynamicService;
import com.hanhai.zrb.api.biz.service.UserInfoService;
import com.hanhai.zrb.api.biz.service.UserService;
import com.hanhai.zrb.model.common.PageList;
import com.hanhai.zrb.model.message.MessageInfo;
import com.hanhai.zrb.model.message.MessageReceive;
import com.hanhai.zrb.model.project.Industry;
import com.hanhai.zrb.model.user.User;
import com.hanhai.zrb.model.user.dto.UserSearchDto;
import com.hanhai.zrb.model.user.enums.UserInfoName;
import com.hanhai.zrb.model.user.vo.UserInfoVO;
import com.hanhai.zrb.model.userDynamic.UserDynamic;
import com.hanhai.zrb.model.userDynamic.dto.UserDynamicDto;

@Controller
@RequestMapping("/user")
public class UserController {

	@Resource
	private UserInfoService userInfoService;
	@Resource
	private UserService userService;
	@Resource
	private CityInfoService cityInfoService;
	@Resource
	private IndustryService industryService;
	@Resource
	private UserDynamicService userDynamicService;
	@Resource
	private SysDictionaryService sysDictionaryService;

	@Resource
	private UserBlacklistService userBlacklistService;

	@Resource
	private MessageQueryService messageQueryService;

	@RequestMapping("/index")
	public String index() {
		return "user/index";
	}

	@RequestMapping("/list")
	@ResponseBody
	public String list(UserSearchDto dto, Integer page, Integer rows) {
		Map<String, Object> map = Maps.newHashMap();
		PageInfo pageInfo = userService.queryUserBySearchDto(dto, page, rows);
		if (pageInfo != null) {
			map.put("rows", pageInfo.getList());
			map.put("total", pageInfo.getTotal());
		} else {
			map.put("rows", Lists.newArrayList());
			map.put("total", 0);
		}
		return JSON.toJSONString(map);
	}

	@RequestMapping("/listNotInBlacklist")
	@ResponseBody
	public String listNotInBlacklist(UserSearchDto dto, Integer page,
			Integer rows) {
		List<Long> userIdList = userBlacklistService.listAllUserId();
		if (CollectionUtils.isNotEmpty(userIdList)) {
			dto.setUidListNotIn(userIdList);
		}
		return list(dto, page, rows);
	}

	@RequestMapping("/indexDynamic")
	public String indexDynamic(Long id, HttpServletRequest request,
			HttpServletResponse response) {
		request.setAttribute("id", id);
		return "user/indexDynamic";
	}

	@RequestMapping("/getDynamicList")
	@ResponseBody
	public String getDynamicList(Long id, Integer page, Integer rows) {
		Map<String, Object> map = Maps.newHashMap();
		PageList<UserDynamic> pageList = new PageList<>();
		List<UserDynamic> list = new ArrayList<UserDynamic>();
		if (null != id) {
			UserDynamicDto dto = new UserDynamicDto();
			dto.setUserId(id);
			pageList = userDynamicService.queryPageByDto(dto, page, rows);
			list = pageList.getList();
			userDynamicService.batchConverExtraDateForView(list);
		}

		if (pageList != null) {
			map.put("rows", list);
			map.put("total", pageList.getTotal());
		} else {
			map.put("rows", Lists.newArrayList());
			map.put("total", 0);
		}
		return JSON.toJSONString(map);
	}

	@RequestMapping("/deleteDynamic")
	@ResponseBody
	public String deleteDynamic(String ids){
		boolean ret = true ;
		Map<String, Object> map = Maps.newHashMap();
		
	   	if(StringUtils.isNotBlank(ids) ){
	   		List<Long> idList = new ArrayList();
			String[] str = ids.split(",");
			for (int i = 0; i < str.length; i++) {
				if(StringUtils.isNumeric(str[i])){
					idList.add(Long.valueOf(str[i]));
				}
			}
	   		ret = userDynamicService.deleteDynamic(idList);;
	   	}else{
	   		ret = false;
	   	}
		if(ret){
			map.put("success", true);
			map.put("infoMsg", "删除信息成功");
		}else{
			map.put("success", false);
			map.put("errorMsg", "删除信息失败,请稍后再试");
		}   	
		return JSON.toJSONString(map);
	}
	
	@RequestMapping("/indexMessage")
	public String indexMessage(Long id, HttpServletRequest request,
			HttpServletResponse response) {
		request.setAttribute("id", id);
		return "user/indexMessage";
	}

	@RequestMapping("/getUserMessage")
	@ResponseBody
	public String getUserMessage(Long id, Integer rows, Integer page) {
		Map<String, Object> map = Maps.newHashMap();
		PageInfo pageInfo = messageQueryService.queryPageReceiveMessage(id,
				null, rows, page);

		if (pageInfo != null) {
			map.put("rows", pageInfo.getList());
			map.put("total", pageInfo.getTotal());
		} else {
			map.put("rows", Lists.newArrayList());
			map.put("total", 0);
		}
		return JSON.toJSONString(map);
	}

	// 如果是按标准格式，是自动可以转，如果是其他格式才String接收
	@InitBinder
	protected void initBinder(WebDataBinder binder) throws ServletException {

		DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
		fmt.setLenient(false);

		CustomDateEditor dateEditor = new CustomDateEditor(fmt, true);
		binder.registerCustomEditor(Date.class, dateEditor);

		CustomCollectionEditor collectionEditor = new CustomCollectionEditor(
				List.class, true);

		binder.registerCustomEditor(List.class, collectionEditor);
	}

	// 更改会员状态
	@RequestMapping(value = "/updateStatus", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String updateStatus(String ids, String status) {
		boolean ret = true;
		Map<String, Object> map = Maps.newHashMap();
		if (StringUtils.isNotBlank(ids) && StringUtils.isNotBlank(status)) {
			List<Long> idList = Lists.newArrayList();
			String[] str = ids.split(",");
			for (int i = 0; i < str.length; i++) {
				if (StringUtils.isNumeric(str[i])) {
					idList.add(Long.valueOf(str[i]));
				}
			}
			ret = userService.upageStatus(idList, status);
		} else {
			ret = false;
		}
		if (ret) {
			map.put("success", true);
			map.put("msg", "修改信息成功");
		} else {
			map.put("success", false);
			map.put("msg", "修改信息失败,请稍后再试");
		}
		return JSON.toJSONString(map);
	}

	// 保存会员信息
	@RequestMapping(value = "/saveUser", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String saveUser(String uid, String industryId, String provinceId,
			String cityIds, String realname, String org, String position,
			String depict) {
		Map<String, Object> map = Maps.newHashMap();
		User user = new User();
		user.setUid(Long.valueOf(uid));
		if (StringUtils.isNumeric(industryId)) {
			Industry ins = industryService.selectByPrimaryKey(Integer
					.valueOf(industryId));
			if (null != ins) {
				user.setIndustryId(Long.valueOf(ins.getId()));
				user.setIndustry(ins.getIndustryName());
			}
		}
		user.setDepict(depict);
		if (StringUtils.isNotBlank(realname)) {
			user.setRealname(realname);
		}

		if (StringUtils.isNotBlank(org)) {
			user.setOrg(org);
		}
		try {
			userService.update(user);
			map.put("success", true);
			map.put("msg", "修改信息成功");
		} catch (Exception e) {
			map.put("success", false);
			map.put("msg", "修改信息失败,请稍后再试");
		}

		if (StringUtils.isNotBlank(provinceId)
				|| StringUtils.isNotBlank(cityIds)
				|| StringUtils.isNotBlank(position)) {
			UserInfoVO vo = new UserInfoVO();
			Map<String, String> mapVo = new HashMap<String, String>();
			vo.setUserId(uid);

			if (StringUtils.isNumeric(cityIds)) {
				mapVo.put(UserInfoName.LOCATION.name(), cityIds);
			}
			if (StringUtils.isNotBlank(position)) {
				mapVo.put(UserInfoName.POSITION.name(), position);
			}
			vo.setInfoMap(mapVo);
			try {
				userInfoService.batchSave(vo);
				map.put("success", true);
				map.put("msg", "修改信息成功");
			} catch (Exception e) {
				map.put("success", false);
				map.put("msg", "修改信息失败,请稍后再试");
			}
		}

		return JSON.toJSONString(map);
	}

}
